package com.situ.gym.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mysql.cj.log.Log;
import com.situ.gym.pojo.Admin;
import com.situ.gym.pojo.dto.AdminPasswordDTO;
import com.situ.gym.pojo.dto.LoginInfoDTO;
import com.situ.gym.pojo.query.AdminQuery;
import com.situ.gym.service.IAdminService;
import com.situ.gym.util.JwtUtil;
import com.situ.gym.util.Result;
import com.situ.gym.util.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private IAdminService adminService;
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/selectAssignRole/{adminId}")
    public Result selectAssignRole(@PathVariable Integer adminId) {
        //List<Role> roleList;
        //List<Long> assignedRoleIdList;
        Map<String, Object> map =  adminService.selectAssignRole(adminId);
        return Result.ok(map);
    }

    @PostMapping("/assignRole")
    public Result assignRole(Long adminId, Long[] roleIds) {
        adminService.assignRole(adminId, roleIds);
        return Result.ok("分配成功");
    }

    @PutMapping("/resetPassword")
    public Result resetPassword(@RequestBody AdminPasswordDTO adminPasswordDTO,
                                @RequestHeader(name = "Authorization")String token) {
        //Map<String, Object> map = JwtUtil.parseToken(token);
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        Admin admin = adminService.getById(id);
        //先判断就密码是否正确
        if (!admin.getPassword().equalsIgnoreCase(adminPasswordDTO.getOldPassword())) {
            return Result.error("旧密码错误");
        }

        Admin adminUpdate = new Admin();
        adminUpdate.setId(admin.getId());
        adminUpdate.setPassword(adminPasswordDTO.getNewPassword());
        adminService.updateById(adminUpdate);
        return Result.ok("更新成功");

    }


    @GetMapping("/adminInfo")
    public Result adminInfo(@RequestHeader(name = "Authorization")String token) {
        //Map<String, Object> map = JwtUtil.parseToken(token);
        Map<String, Object> tokenMap = ThreadLocalUtil.get();
        //Long.valueOf(map.get("id").toString())
        Integer id = (Integer) tokenMap.get("id");
        //Admin admin = adminService.getById(id);
        //admin.setPassword(null);
        //除了有Admin，还有这个用户的所有权限信息
        Map<String, Object> map = adminService.selectAdminPermissionInfoById(id);
        return Result.ok(map);
    }

    @PostMapping("/login")
    public Result login(@RequestBody LoginInfoDTO loginInfoDTO) {
        //首先判断验证码是否正确
        String captcha = (String) redisTemplate.opsForValue().get("captcha:" + loginInfoDTO.getUuid());
        if (ObjectUtils.isEmpty(captcha)) {
            return Result.error("验证码已经过期");
        }
        if (!captcha.equalsIgnoreCase(loginInfoDTO.getCaptcha())) {
            return Result.error("验证码错误");
        }

        //名字是唯一的
        Admin loginAdmin = adminService.selectByName(loginInfoDTO.getName());
        if (loginAdmin == null) {
            return Result.error("用户名错误");
        }

        //判断密码是否正确
        if (!loginInfoDTO.getPassword().equals(loginAdmin.getPassword())) {
            return Result.error("密码错误");
        }

        //是否禁用
        if (loginAdmin.getStatus() == 0) {
            return Result.error("该用户已经被禁用");
        }

        //登录成功
        Map<String, Object> map = new HashMap<>();
        map.put("id", loginAdmin.getId());
        map.put("name", loginAdmin.getName());
        String token = JwtUtil.createToken(map);
        return Result.ok("登录成功", token);
    }

    //Restful    GET(查找)、POST(添加)、DELETE(删除)、PUT(修改)
    //@RequestMapping("/list")
    //@RequestMapping(value = "/list", method = {RequestMethod.GET, RequestMethod.POST})
    //@RequestMapping(value = "/list", method = RequestMethod.GET)
    @GetMapping("/list")
    public Result<IPage<Admin>> list(AdminQuery adminQuery) {
        System.out.println("AdminController.list");
        IPage<Admin> page = adminService.list(adminQuery);
        return Result.ok(page);
    }

    // /deleteById?id=1
    // /deleteById/1
    @DeleteMapping("/deleteById/{id}")
    public Result deleteById(@PathVariable Integer id) {
        adminService.removeById(id);
        return Result.ok("删除成功");
    }

    // /deleteAll/1,2,3
    @DeleteMapping("/deleteAll/{ids}")
    public Result deleteAll(@PathVariable Integer[] ids) {
        //adminService.removeBatchByIds(Arrays.asList(ids));
        adminService.deleteAll(ids);
        return Result.ok("删除成功");
    }

    /*@PostMapping("/add")
    public Result add(Admin admin) {
        System.out.println(admin);
        return Result.ok();
    }*/

    // @RequestBody : 封装前台传递过来的JSON格式数据
    // @ResponseBody : 将数据转换为JSON格式返回
    @PostMapping("/add")
    public Result add(@RequestBody Admin admin) {
        System.out.println(admin);
        adminService.save(admin);
        return Result.ok("添加成功");
    }

    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable Integer id) {
        Admin admin = adminService.getById(id);
        return Result.ok(admin);
    }

    @PutMapping("/update")
    public Result update(@RequestBody Admin admin) {
        System.out.println(admin);
        //adminService.saveOrUpdate(admin);
        adminService.updateById(admin);
        return Result.ok("更新成功");
    }

    @PutMapping("/updateStatus/{id}/{status}")
    public Result updateStatus(@PathVariable Long id, @PathVariable Integer status) {
        Admin admin = new Admin();
        admin.setId(id);
        admin.setStatus(status);
        adminService.updateById(admin);
        return Result.ok("修改成功");
    }
}

